const DB = require('../../utils/db');
const JWT = require('../../utils/jwt');
const { getKey, setKey, delKey } = require('../../utils/redis');
const { cosUpload, cosDelete } = require('../../utils/oss');
const path = require('path');
const { ipv6ToV4 } = require('../../utils/utlis');
const IP2Region = require('ip2region').default;
const query = new IP2Region();
const eventEmitter = require('../../utils/events');

// 文件夹名称
let ossDirectory = 'avatar';

module.exports = {
	register: async (email, username, password, code, captchaKey) => {
		// 查看验证码
		let svgCode = await getKey(captchaKey);

		if (!svgCode) throw new Error('验证码已过期');
		if (svgCode.toLocaleUpperCase() != code.toLocaleUpperCase()) throw new Error('验证码错误');
		// 查看当前用户是否存在
		let sql = 'select * from t_user where email=? and type=1';

		let [list] = await DB.query(sql, [email]);

		if (list.length) throw new Error('当前用户已存在');
		// 注册，并给默认值
		let sql1 = "insert into t_user (email,username,password,avatar,type) values(?,?,?,'/uploads/avatar/nv.png',1)";
		DB.query(sql1, [email, username, password]);

		// 删除缓存的key
		await delKey(captchaKey);
	},
	login: async (email, password, code, captchaKey, ipv6) => {
		// ipv6转ipv4
		let ip = ipv6ToV4(ipv6);
		const { country, province, city, isp } = query.search(ipv6);

		// 查看验证码
		let svgCode = await getKey(captchaKey);
		if (!svgCode) throw new Error('验证码已过期');
		if (svgCode.toLocaleUpperCase().trim() != code.toLocaleUpperCase().trim()) throw new Error('验证码错误');

		// 检查用户是否存在
		let sql = 'select * from t_user where email=?and type=1';
		let [list] = await DB.query(sql, [email]);
		if (!list.length) throw new Error('当前用户不存在');
		// 判断密码
		if (list[0].password != password) throw new Error('密码错误');
		// 生成token
		let { id } = list[0];
		let token = JWT.encrypt({ id });
		delete list[0].password;

		// 存储ip信息
		await DB.query('update t_user set ip=?,country=?,province=?,city=?,isp=? where id=?', [ip, country, province, city, isp, id]);

		// sse 发送 用户数量统计
		let [userList] = await DB.query('select count(1) num from t_user  where type=1');
		// 实时用户省份统计
		let [provinceList] = await DB.query(`select province,count(1) num from t_user where type=1 group by province`);
		eventEmitter.emit('userNums', { userNums: userList[0].num, provinceList });
            

		return { token, info: list[0] };
	},
	forget: async (email, password, code, captchaKey) => {
		// 查看验证码
		let svgCode = await getKey(captchaKey);
		if (!svgCode) throw new Error('验证码已过期');
		if (svgCode.toLocaleUpperCase().trim() != code.toLocaleUpperCase().trim()) throw new Error('验证码错误');

		// 检查用户是否存在
		let sql = 'select * from t_user where email=?and type=1';
		let [list] = await DB.query(sql, [email]);
		if (!list.length) throw new Error('当前用户不存在');

		// 修改密码
		await DB.query('update t_user set password=? where email=? and type=1', [password, email]);

		return true;
	},
	userInfo: async (id) => {
		let [list] = await DB.query(`select * from t_user where id=? `, [id]);
		delete list[0].password;
		return list[0];
	},
	update: async (avatar, filename, username, password, gender, website, weixin, mobile, id) => {
		await DB.query('update t_user set username=?, gender=?, website=?, weixin=?,mobile=? where id=?', [username, gender, website, weixin, mobile, id]);

		if (password) {
			// 修改密码
			await DB.query('update t_user set password=? where id=?', [password, id]);
		}

		if (filename) {
			let [list] = await DB.query('select * from t_user where id=?', [id]);
			// 先删除头像
			await cosDelete(ossDirectory, path.basename(list[0].avatar));
			// 上传oss
			let { Location } = await cosUpload(ossDirectory, filename);

			// oss 全路径
			let fullUrl = 'https://' + Location;
			// 修改头像
			await DB.query('update t_user set avatar=? where id=?', [fullUrl, id]);
		}
	},
	del: async (id) => {
		// 估计这里有问题，是否需要删除其他的表
		await DB.query('delete from t_user where id =?', [id]);
	},
	getBloger: async () => {
		let [list] = await DB.query('select content from t_bloger where id=1');
		return list[0];
	}
};
